﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

public class UIRollCustom : MonoBehaviour
{
    public enum ComponentType {
        Text,
        Slider
    }

    public ComponentType compType = ComponentType.Text;

    private float value;

    [SerializeField]
    private float _targetValue;
    [SerializeField]
    public float targetValue
    {
        get
        {
            return _targetValue;
        }
        set
        {
            _targetValue = value;
            Scroll();
        }
    }

    [Range(0, 0.5f), Tooltip("Lerp取值，越小越慢")]
    public float lerpValue = 0.1f;
    public bool playAtStart = true;
    [Range(0, 1.0f), Tooltip("滚动之前会等待几秒钟")]
    public float runWaitTimer = 0;

    private bool isScrolling = false;
    private bool isDelayWait = false;

    [Tooltip("滚动开始时的事件")]
    public UnityEvent scrollStartEvent = null;

    [Tooltip("滚动停止时的事件")]
    public UnityEvent scrollEndEvent = null;

    #if UNITY_EDITOR
     private void OnValidate() {
         Scroll();
     }
    #endif

    private void Awake()
    {
        if (playAtStart)
        {
            UpdateComp();
            Scroll();
        }
    }


    public void Scroll()
    {
        if(this.isScrolling)return;
        if(this.runWaitTimer>0){
            if(!this.isDelayWait){
                Invoke("ActiveScroll",runWaitTimer);
            }
        }else{
            ActiveScroll();
        }
    }

    public void ScrollTo(float target)
    {
        targetValue = target;
    }

    public void Stop(){
        value = targetValue;
        CancelInvoke("ActiveScroll");
        isDelayWait = false;
        isScrolling = false;
        UpdateComp();
    }

    private void ActiveScroll(){
        isDelayWait = false;
        isScrolling = true;
    }


    private void UpdateComp(){
        var value  = this.value;
        switch (this.compType)
        {
            case ComponentType.Slider:
                if(this.GetComponent<Slider>())this.GetComponent<Slider>().value = value;
                break;
            default:
                break;
        }
 
    }

    // Update is called once per frame
    void Update()
    {
        if(isScrolling == false)return;
        var dt = Time.deltaTime;
        var scale = (dt *60 );
        this.value = Mathf.Lerp(value,_targetValue,lerpValue * scale);

        UpdateComp();
        
        if(Mathf.Abs(this.value - this._targetValue)<=0.001f){
            this.value = this._targetValue;
             scrollEndEvent.Invoke();
             isScrolling = false;
            return;
        }

    }
}
